<template>
  <view class="content">
    <div class="uploadId">
      <h3><span>*</span>上传身份证</h3>
      <p>1，身份证必须为大陆公民持有的有效二代身份证</p>
      <p>2，请确保身份证边框清晰，字迹完整，证件号码清晰可见</p>
      <div class="upload">
        <view class="id1" @click="(e) => uploadImg(e, '0')">
          <image
            :src="fromImgs['0'] || '../static/上传身份证正面.png'"
            mode="widthFix"
            @load="imgLoading"
          ></image>
          上传身份证正面
        </view>
        <view class="id1" @click="(e) => uploadImg(e, '1')">
          <image
            @load="imgLoading"
            :src="fromImgs['1'] || '../static/上传身份证反面.png'"
            mode="widthFix"
          ></image>
          上传身份证反面
        </view>
        <view class="id1" @click="(e) => uploadImg(e, '2')">
          <image
            @load="imgLoading"
            :src="fromImgs['2'] || '../static/手持身份证照片.png'"
            mode="widthFix"
          ></image>
          手持身份证照片
        </view>
      </div>
      <div class="formbox">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
          <!-- 必填项 -->
          <u-form-item
            v-for="item in requiredFields"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            borderBottom
            required
            labelWidth="80"
          >
            <u-input
              v-model="form[item.prop]"
              :placeholder="`请输入${item.label}`"
              :type="item.type || 'text'"
              border="none"
            />
          </u-form-item>

          <!-- 非必填项 -->
          <u-form-item
            v-for="item in optionalFields"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            borderBottom
            labelWidth="80"
          >
            <u-input
              v-model="form[item.prop]"
              :placeholder="`请输入${item.label}`"
              :type="item.type || 'text'"
              border="none"
            />
          </u-form-item>
        </u--form>
      </div>
      <u-button @click="submit" color="#4baf4f">提交</u-button>
    </div>
  </view>
</template>

<script>
const idCardRegex =
  /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
import { upload, save } from "../api/index.js";
export default {
  data() {
    return {
      form: {
        credit_limit: "", // 申请额度
        id_card_front: "", // 身份证正面
        id_card_back: "", // 身份证反面
        id_card_hand: "", // 身份证手持
        name: "", // 姓名
        id_card_no: "", // 身份证
        phone: "", // 电话号码
        address: "", // 地址
        zhima_score: "", // 芝麻分
        huabei_credit_limit: "", // 花呗
        jiebei_credit_limit: "", // 借呗
        wangshang_credit_limit: "", // 网商
        provident_fund: "", // 公积金月缴
        wages: "", // 打卡工资
        company_name: "", // 单位名称
        company_phone: "", // 单位电话
        company_address: "", // 单位地址
        spouse_name: "", // 配偶姓名
        spouse_phone: "", // 配偶电话
        spouse_address: "", // 配偶住址
        fa_name: "", // 父亲姓名
        fa_phone: "", // 父亲电话
        fa_address: "", // 父亲地址
        mo_name: "", // 母亲姓名
        mo_phone: "", // 母亲电话
        mo_address: "", // 母亲地址
      },
      requiredFields: [
        { label: "申请额度", prop: "credit_limit", type: "number" },
        { label: "姓名", prop: "name" },
        { label: "身份证号码", prop: "id_card_no", type: "idcard" },
        { label: "电话", prop: "phone", type: "number" },
        { label: "地址", prop: "address" },
        { label: "芝麻分", prop: "zhima_score", type: "number" },
        { label: "花呗额度", prop: "huabei_credit_limit", type: "number" },
        { label: "借呗额度", prop: "jiebei_credit_limit", type: "number" },
        { label: "网商贷额度", prop: "wangshang_credit_limit", type: "number" },
        { label: "公积金月缴", prop: "provident_fund", type: "number" },
        { label: "打卡工资", prop: "wages", type: "number" },
        { label: "单位名称", prop: "company_name" },
        { label: "单位电话", prop: "company_phone", type: "number" },
        { label: "单位地址", prop: "company_address" },
      ],
      optionalFields: [
        { label: "配偶姓名", prop: "spouse_name" },
        { label: "配偶电话", prop: "spouse_phone", type: "number" },
        { label: "配偶住址", prop: "spouse_address" },
        { label: "父亲姓名", prop: "fa_name" },
        { label: "父亲电话", prop: "fa_phone", type: "number" },
        { label: "父亲住址", prop: "fa_address" },
        { label: "母亲姓名", prop: "mo_name" },
        { label: "母亲电话", prop: "mo_phone", type: "number" },
        { label: "母亲住址", prop: "mo_address" },
      ],
      rules: {
        credit_limit: {
          type: "number",
          required: true,
          message: "请填写申请额度",
          trigger: ["blur", "change"],
        },
        name: [
          {
            type: "string",
            required: true,
            message: "请填写姓名",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return value.length <= 6;
            },
            message: "姓名最多6个字符",
            trigger: ["blur", "change"],
          },
        ],
        id_card_no: [
          {
            type: "string",
            required: true,
            message: "请填写身份证号码",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              if (!idCardRegex.test(value)) {
                callback(new Error("身份证格式错误"));
              } else if (!validateChecksum(value)) {
                callback(new Error("校验码不合法"));
              } else if (!validateAreaCode(value)) {
                // 地区码校验
                callback(new Error("无效的地区码"));
              } else if (!validateBirthday(value)) {
                // 日期有效性校验
                callback(new Error("无效的出生日期"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: false,
            message: "电话不能为空",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              return /^1\d{10}$/.test(value);
            },
            message: "手机号格式不正确",
            trigger: ["blur"],
          },
        ],
        provident_fund: {
          type: "number",
          required: true,
          message: "请填写公积金月缴",
          trigger: ["blur", "change"],
        },
        wages: {
          type: "number",
          required: true,
          message: "请填写打卡工资",
          trigger: ["blur", "change"],
        },
        company_name: [
          {
            type: "string",
            required: true,
            message: "请填写单位名称",
            trigger: ["blur", "change"],
          },
          {
            trigger: ["blur", "change"],
          },
        ],
        company_phone: [
          {
            required: true,
            message: "单位电话不能为空",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              return /^1\d{10}$/.test(value);
            },
            message: "手机号格式不正确",
            trigger: ["blur"],
          },
        ],
        company_address: [
          {
            type: "string",
            required: true,
            message: "请填写单位地址",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return value.length <= 18;
            },
            message: "地址最多18个字符",
            trigger: ["blur", "change"],
          },
        ],
        address: [
          {
            type: "string",
            required: true,
            message: "请填写地址",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return value.length <= 18;
            },
            message: "地址最多18个字符",
            trigger: ["blur", "change"],
          },
        ],
        zhima_score: {
          type: "number",
          required: true,
          message: "请填写芝麻分",
          trigger: ["blur", "change"],
        },
        huabei_credit_limit: {
          type: "number",
          required: true,
          message: "请填写花呗额度",
          trigger: ["blur", "change"],
        },
        jiebei_credit_limit: {
          type: "number",
          required: true,
          message: "请填写借呗额度",
          trigger: ["blur", "change"],
        },
        wangshang_credit_limit: {
          type: "number",
          required: true,
          message: "请填写网贷商额度",
          trigger: ["blur", "change"],
        },
      },
      fileList6: [],
      fromImgs: {
        0: "",
        1: "",
        2: "",
      },
    };
  },
  onLoad() {},
  methods: {
    // 表单提交
    submit() {
      this.$refs.uForm
        .validate()
        .then((res) => {
          const imgs = Object.values(this.fromImgs);
          const isValid =
            imgs.length === 3 && imgs.every((item) => item !== "");
          if (isValid) {
            uni.$u.toast("校验通过");
            this.form.id_card_front = imgs[0];
            this.form.id_card_back = imgs[1];
            this.form.id_card_hand = imgs[2];

            uni.showLoading({
              title: "提交中...",
              mask: true,
            });
            save(this.form)
              .then((r) => {
                if (r?.code === 0) {
                  uni.$u.toast("提交成功");
                  setTimeout(() => {
                    uni.reLaunch({ url: "end" });
                  }, 1000);
                }
                uni.hideLoading();
              })
              .catch(() => {
                uni.$u.toast("提交失败");
                uni.hideLoading();
              });
          } else {
            uni.$u.toast("请上传身份证照片");
          }
        })
        .catch((errors) => {
          uni.$u.toast("校验失败");
        });
    },
    // 表单重制
    formReset() {},
    // 上传图片
    uploadImg(e, index) {
      let that = this;
      const tokens = uni.getStorageSync("massageToken");
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          // console.log(tempFilePaths, "----------------------");
          // uni.compressImage
          uni.showLoading({
            title: "图片上传中...",
            mask: true,
          });
          uni.uploadFile({
            url: "http://118.31.185.103:9090/api/upload", //仅为示例，非真实的接口地址
            header: { Authorization: tokens ? "bearer " + tokens : "" },
            filePath: tempFilePaths[0],
            name: "file",
            formData: {
              user: "test",
            },
            success: (uploadFileRes) => {
              this.fromImgs[index] = JSON.parse(uploadFileRes.data)?.data || "";
            },
            fail: (err) => {
              uni.$u.toast("图片上传失败");
              uni.hideLoading();
            },
          });
        },
      });
    },
    imgLoading() {
      uni.hideLoading();
    },
    validateChecksum(id) {
      const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
      const parity = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]; // 校验码对照表
      let sum = 0;
      for (let i = 0; i < 17; i++) {
        sum += parseInt(id[i]) * factors[i];
      }
      return parity[sum % 11] === id[17].toUpperCase();
    },
    validateAreaCode() {
      const provinceCodes = [
        "11",
        "12",
        "13",
        "14",
        "15",
        "21",
        "22",
        "23",
        "31",
        "32",
        "33",
        "34",
        "36",
        "37",
        "41",
        "42",
        "43",
        "44",
        "45",
        "46",
        "50",
        "51",
        "52",
        "53",
        "54",
        "61",
        "62",
        "63",
        "64",
        "65",
      ];
      return provinceCodes.includes(id.substr(0, 2));
    },
    validateBirthday() {
      const year = parseInt(id.substr(6, 4));
      const month = parseInt(id.substr(10, 2)) - 1;
      const day = parseInt(id.substr(12, 2));
      const date = new Date(year, month, day);
      return (
        date.getFullYear() === year &&
        date.getMonth() === month &&
        date.getDate() === day
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  width: 100vw;
  position: relative;
  background: #fff;
  .uploadId {
    width: 100%;
    padding: 10px 25px;
    padding-bottom: 25px;
    h3 {
      margin-bottom: 5px;
      margin-top: 10px;
      span {
        color: red;
      }
    }
    p {
      color: #555;
      margin-bottom: 5px;
      font-size: 15px;
    }
  }
  .upload {
    width: 100%;
    display: flex;
    // flex-direction: column;
    align-items: center;
    margin-top: 15px;
    .id1 {
      // width: 200px;
      flex: 1;
      margin: 0 5px;
      text-align: center;
      margin-bottom: 10px;
      image {
        width: 100%;
        height: 62px !important;
        border-radius: 10px;
        overflow: hidden;
        margin-bottom: 5px;
        box-shadow: 0 4px 10px #d0e3f1;
      }
    }
    ::v-deep uni-view {
      width: 100%;
      flex-direction: row;
    }
  }
  .formbox {
    margin: 10px 0;
    padding: 0 10px;
    margin-bottom: 15px;
    ::v-deep .u-form-item {
      height: 60px;
    }
  }
  ::v-deep .u-button {
    height: 45px;
    border-radius: 10px;
    background: linear-gradient(90deg, #b0d8fc, #98bcff);
    border-color: transparent !important;
    margin-bottom: 10px;
    font-size: 20px;
  }
}
</style>
